package top.maohh.study.demo.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import top.maohh.study.demo.zookeeper.config.ZookeeperConfig;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * zookeeper 案例测试
 *
 * @author maohh
 */
public class ZookeeperMain implements Watcher {
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();
    // countDownLatch 参考资料: https://www.jianshu.com/p/e233bb37d2e6
    // 主要用来控制线程同步使用
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        //zookeeper配置数据存放路径
        String path = "/zk01";
        //连接zookeeper并且注册一个默认的监听器
        zk = new ZooKeeper(ZookeeperConfig.ZK_ADDRESS, ZookeeperConfig.ZK_TIMEOUT, new ZookeeperMain());
        //等待zk连接成功的通知
        connectedSemaphore.await();
        //获取path目录节点的配置数据，并注册默认的监听器
        // 这里监听的关键词是watch
        System.out.println(new String(zk.getData(path, true, stat)));
        System.out.println(new String(zk.getData(path + "/mother", true, stat)));

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        //zk连接成功通知事件
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            }
            //zk目录节点数据变化通知事件
            else if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    // 这里需要你去zookeeper中去更新状态,更新状态之后这里会进行变更
                    System.out.println(event.getPath() + "配置已修改，新值为：" + new String(zk.getData(event.getPath(), true, stat)));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
}
